// pages/addTodo/addTodo.js
const db = wx.cloud.database();
const todos = db.collection('todos');
Page({
  data:{
    image: null
  },
  pageData:{
    locationObj: {}
  },
  selectImage:function(e) {
    wx.chooseImage({
      success: res => {
        wx.cloud.uploadFile({
          cloudPath:`${Math.floor(Math.random()*10000000)}.png`,
          filePath: res.tempFilePaths[0]
        }).then(res => {
          this.setData({
            image: res.fileID
          })
        }).catch(err => {
          console.error(err)
        })
      },
    })
  },
  bindTimeChange:function(event) {
    this.setData({
      time: event.detail.value
    })
  },
  onSubmit: function (event){
    // console.log(e.detail.formId)
    let myDate = new Date;
    let month = myDate.getMonth() + 1;
    let day = myDate.getDay();
    let year = myDate.getFullYear();
    let time = `${year}-${month}-${day} ${this.data.time}`

    todos.add({
      data:{
        title: event.detail.value.title,
        image: this.data.image,
        location: this.pageData.locationObj,
        status: 'in-progress',
        time: time,
        formId: event.detail.formId
      }
    }).then(res => {
      wx.showToast({
        title: 'Success',
        icon: 'success',
        success: res2 =>{
          wx.redirectTo({
            url: `../todoinfo/todoinfo?id=${res._id}`,
          })
        }
      })
    })
  },
  chooseLocation:function(e) {
    wx.chooseLocation({
      success: res => {
        let locationObj = {
          latitude: res.latitude,
          longitude: res.longitude,
          name: res.name,
          address: res.address
        }
        this.pageData.locationObj = locationObj
      },
    })
  }
})